﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.IO.Ports;
using System.Windows.Forms;

namespace Project1
{
    public class CommunicationManager
    {
        private SerialPort comPort = new SerialPort();

        public static void Main()
        {
            CommunicationManager com1 = new CommunicationManager(); //we are using COM1
            com1.OpenPort();
            while (true)
            {
                com1.WriteData("20");  //This number is 20 in Hex, 32 in decimal, and 10,000 in binary
            }
        }
        /// <summary>
        /// Constructor to set the properties of our Manager Class
        /// </summary>
        /// <param name="baud">Desired BaudRate</param>
        /// <param name="par">Desired Parity</param>
        /// <param name="sBits">Desired StopBits</param>
        /// <param name="dBits">Desired DataBits</param>
        /// <param name="name">Desired PortName</param>

        public void WriteData(string msg)
        {            
                    try
                    {
                        //convert the message to byte array
                        byte[] newMsg = HexToByte(msg);
                        //send the message to the port
                        comPort.Write(newMsg,0,newMsg.Length);
                        //convert back to hex and display
                        
                    }
                    catch (FormatException ex)
                    {
                        //display error message
                        //DisplayData(MessageType.Error, ex.Message);	jeffasth@frontiernet.net
                    }
        }
       
        public enum TransmissionType { Text, Hex }
        private TransmissionType _transType;
        

        
        public TransmissionType CurrentTransmissionType
        {
            get { return _transType; }
            set { _transType = value; }
        }


        /// <summary>
        /// method to convert hex string into a byte array
        /// </summary>
        /// <param name="msg">string to convert</param>
        /// <returns>a byte array</returns>

        private byte[] HexToByte(string msg)
        {
            //remove any spaces from the string
            msg = msg.Replace(" ", "");
            //create a byte array the length of the
            //string divided by 2
            byte[] comBuffer = new byte[msg.Length / 2];
            //loop through the length of the provided string
            for (int i = 0; i < msg.Length; i += 2)
                //convert each set of 2 characters to a byte
                //and add to the array
                comBuffer[i / 2] = (byte)Convert.ToByte(msg.Substring(i, 2), 16);          
            //return the array
            return comBuffer;
        }
        
        /// <summary>
        /// method to convert a byte array into a hex string
        /// </summary>
        /// <param name="comByte">byte array to convert</param>
        /// <returns>a hex string</returns>

        private string ByteToHex(byte[] comByte)
        {
            //create a new StringBuilder object
            StringBuilder builder = new StringBuilder(comByte.Length * 3);
            //loop through each byte in the array
            foreach (byte data in comByte)
                //convert the byte to a string and add to the stringbuilder
                builder.Append(Convert.ToString(data, 16).PadLeft(2, '0').PadRight(3, ' '));
            //return the converted value
            return builder.ToString().ToUpper();
        }


        void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
                    int bytes = comPort.BytesToRead;
                    //create a byte array to hold the awaiting data
                    byte[] comBuffer = new byte[bytes];
                    //read the data and store it
                    comPort.Read(comBuffer, 0, bytes);
                    //display the data to the user
        }


        public bool OpenPort()
        {
            try
            {
                //first check if the port is already open
                //if its open then close it
                if (comPort.IsOpen == true) comPort.Close();
               
                //now open the port
                comPort.Open();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
         }  
    }
}
